<template>
    <div
        class="view-time-table"
        :style="{
            border: detail.style.waterBorderWidth + 'px solid !important',
            borderRadius: detail.style.borderRadius + 'px !important',
            borderColor: detail.style.waterBorderColor,
        }"
        :id="detail.identifier"
    >
        <el-form v-if="detail.dataBind.tableType === 2" class="form-wrap" :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item prop="dayDaterange">
                <el-date-picker
                    :style="{ width: '340px', color: detail.style.foreColor }"
                    v-model="queryParams.dayDaterange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :picker-options="pickerOptions"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="handleResetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table
            :data="tableList"
            style="width: 100%"
            :cell-style="{ fontSize: detail.style.fontSize + 'px', color: detail.style.foreColor }"
            :header-cell-style="{ fontSize: detail.style.fontSize + 'px', color: detail.style.foreColor }"
            :border="false"
        >
            <template v-for="item in tableColumnList">
                <el-table-column :key="item.id" :type="item.id === 'index' ? 'index' : null" :prop="item.id" :label="item.columnName" align="center"></el-table-column>
            </template>
        </el-table>
        <div class="pag-wrap" v-show="total > 0">
            <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
        <div v-show="false">{{ dataInit }} {{ variableInit }}</div>
    </div>
</template>

<script>
import moment from 'moment';
import { mapState } from 'vuex';

import BaseView from './View';
import { getListVariable, listVariableHistoryTable } from '@/api/scada/topo';

export default {
    name: 'ViewTimeTable',
    extends: BaseView,
    data() {
        return {
            pickerOptions: {
                shortcuts: [
                    {
                        text: '最近2小时',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 200 * 2);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                    {
                        text: '最近一天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 200 * 24);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                    {
                        text: '最近七天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 200 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                    {
                        text: '最近三十天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 200 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                ],
            },
            queryParams: {
                dayDaterange: [new Date(new Date().getTime() - 3600 * 200 * 2), new Date()],
                pageNum: 1,
                pageSize: 10,
            },
            total: 0,
            variableRealList: [
                {
                    serialNum: 'XXX',
                    deviceName: 'XXX',
                    slaveName: 'XXX',
                    modelName: 'XXX',
                    value: 'XXX',
                    unit: 'XXX',
                    ts: 'XXX',
                },
                {
                    serialNum: 'XXX',
                    deviceName: 'XXX',
                    slaveName: 'XXX',
                    modelName: 'XXX',
                    value: 'XXX',
                    unit: 'XXX',
                    ts: 'XXX',
                },
            ],
            variableHistoryList: [
                {
                    serialNum: 'XXX',
                    deviceName: 'XXX',
                    slaveName: 'XXX',
                    modelName: 'XXX',
                    value: 'XXX',
                    unit: 'XXX',
                    ts: 'XXX',
                },
                {
                    serialNum: 'XXX',
                    deviceName: 'XXX',
                    slaveName: 'XXX',
                    modelName: 'XXX',
                    value: 'XXX',
                    unit: 'XXX',
                    ts: 'XXX',
                },
            ],
            thingsModels: [],
        };
    },
    computed: {
        ...mapState({
            mqttData: (state) => state.topoEditor.mqttData,
        }),
        variableInit() {
            const { identifiers, tableType } = this.detail.dataBind;
            if (!this.editMode && identifiers.length !== 0) {
                if (tableType === 1) {
                    this.filterVariable();
                } else {
                    this.getHistoryList();
                }
            }
        },
        tableColumnList() {
            const { tableColumnList } = this.detail.dataBind;
            return tableColumnList;
        },
        tableList() {
            const { tableType } = this.detail.dataBind;
            const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
            const end = start + this.queryParams.pageSize;
            if (tableType === 1) {
                return this.variableRealList.slice(start, end);
            } else {
                return this.variableHistoryList.slice(start, end);
            }
        },
        dataInit() {
            if (Object.keys(this.mqttData).length !== 0) {
                const type = Number(this.$route.query.type);
                let bindNum = this.detail.dataBind.serialNumber;
                let mqttNum = this.mqttData.serialNumber;
                let mqttDeviceId = this.mqttData.sceneModelDeviceId;
                if (type === 1) {
                    bindNum = this.$route.query.serialNumber;
                }
                if (type === 2) {
                    if (mqttNum) {
                        for (let i = 0; i < this.mqttData.message.length; i++) {
                            this.variableRealList.forEach((item) => {
                                if (item.identifier === this.mqttData.message[i].id) {
                                    item.value = this.mqttData.message[i].value;
                                    item.ts = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                                }
                            });
                        }
                    }
                    if (mqttDeviceId) {
                        for (let i = 0; i < this.mqttData.message.length; i++) {
                            this.variableRealList.forEach((item) => {
                                if (item.id === `${mqttDeviceId}-${this.mqttData.message[i].id}`) {
                                    item.value = this.mqttData.message[i].value;
                                    item.ts = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                                }
                            });
                        }
                    }
                } else {
                    if (bindNum && bindNum === mqttNum) {
                        for (let i = 0; i < this.mqttData.message.length; i++) {
                            this.variableRealList.forEach((item) => {
                                if (item.id === this.mqttData.message[i].id) {
                                    item.value = this.mqttData.message[i].value;
                                    item.ts = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                                }
                            });
                        }
                    }
                }
            }
        },
    },
    mounted() {
        this.getVariableList();
    },
    methods: {
        // 查询设备实时数据列表
        getVariableList() {
            const { type, guid } = this.$route.query;
            const params = {
                scadaGuid: guid,
                type: Number(type),
                page: 1,
                size: 9999,
            };
            getListVariable(params).then((res) => {
                if (res.code == 200) {
                    this.thingsModels = res.rows;
                }
            });
        },
        filterVariable() {
            let { type } = this.$route.query;
            type = Number(type);
            const { identifiers, sceneModelDeviceIds, modelValues, modelTimes } = this.detail.dataBind;
            if (type === 2) {
                const list = this.thingsModels.map((item) => ({ ...item, id: item.sceneModelDeviceId + '-' + item.identifier }));
                this.variableRealList = identifiers.map((item, index) => {
                    const data = list.find((chil) => chil.id === `${sceneModelDeviceIds[index]}-${item}`);
                    return { ...data, value: 0 };
                });
            } else {
                const list = this.thingsModels.map((item) => ({ ...item, id: item.identifier }));
                this.variableRealList = identifiers.map((item) => {
                    const data = list.find((chil) => chil.id === item);
                    return { ...data, value: 0 };
                });
            }
            this.variableRealList.forEach((item, index) => {
                item.value = modelValues[index] ? modelValues[index] : 0;
                item.ts = modelTimes[index] ? modelTimes[index] : '---';
            });
            this.total = this.variableRealList.length;
        },
        // 获取历史数据
        getHistoryList() {
            if (this.thingsModels.length !== 0) {
                let { serialNumber, sceneModelId, identifiers } = this.detail.dataBind;
                const type = Number(this.$route.query.type);
                if (type === 1) {
                    serialNumber = this.$route.query.serialNumber;
                }
                if (type === 2) {
                    serialNumber = '';
                }
                const thingsModelList = identifiers.map((item) => {
                    const data = this.thingsModels.find((chil) => chil.identifier === item);
                    const { identifier, type, slaveld, slaveName, sceneModelDeviceId, unit } = data || {};
                    return { identifier, type, slaveld, slaveName, sceneModelDeviceId: sceneModelDeviceId ? Number(sceneModelDeviceId) : null, unit };
                });
                const params = {
                    scadaType: type,
                    sceneModelId: sceneModelId,
                    serialNumber: serialNumber,
                    beginTime: moment(this.queryParams.dayDaterange[0]).format('YYYY-MM-DD HH:mm:ss'),
                    endTime: moment(this.queryParams.dayDaterange[1]).format('YYYY-MM-DD HH:mm:ss'),
                    thingsModelList: thingsModelList,
                };
                listVariableHistoryTable(params).then((res) => {
                    if (res.code == 200) {
                        this.variableHistoryList = res.data;
                        this.total = this.variableHistoryList.length;
                    }
                });
            }
        },
        // 获取列表
        getList(e) {
            this.queryParams.pageNum = e.page;
            this.queryParams.pageSize = e.limit;
        },
        // 查询
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getHistoryList();
        },
        // 重置按钮操作
        handleResetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
    },
};
</script>

<style lang="scss" scoped>
.view-time-table {
    height: 100%;
    width: 100%;
    overflow-y: auto;

    .form-wrap {
        padding: 10px 10px 5px;

        ::v-deep .el-form-item {
            margin-bottom: 0;
        }

        ::v-deep .el-date-editor {
            background-color: transparent;

            .el-range-input {
                color: unset;
                background-color: transparent;
            }
        }
    }

    ::v-deep .el-table {
        background-color: transparent;

        .el-table__header-wrapper {
            background-color: transparent;

            tr {
                background-color: transparent;
                th {
                    background-color: transparent;
                }
            }
        }

        .el-table__body-wrapper {
            background-color: transparent;

            tr {
                background-color: transparent;

                &:hover > td {
                    background-color: transparent;
                }
            }
        }
    }

    .pag-wrap {
        margin: 0 10px 40px;
    }
}
</style>
